package com.zd01.servers;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zd01.anno.LogOperation;
import com.zd01.interfaces.StudentInterface;
import com.zd01.mapper.StudentMapper;
import com.zd01.model.BookModel;
import com.zd01.model.PageResult;
import com.zd01.model.SearchModel;
import com.zd01.model.StudentModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class StudentServer implements StudentInterface {
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageResult<StudentModel> getALL(SearchModel searchModel) {
        PageHelper.startPage(searchModel.getPage(), searchModel.getPageSize());
        List<StudentModel> rows = studentMapper.getALL(searchModel);
        PageInfo<StudentModel> pageInfo = new PageInfo<>(rows);
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getList());
    }
    // 一对多的增加
    @Override
    @LogOperation
    @Transactional(rollbackFor = {Exception.class})
    public void add(BookModel bookModel) {
        // save book 一的关系
        bookModel.setAdd_time(LocalDate.now());
        studentMapper.add(bookModel);

        // save student 多的关系
        List<StudentModel> studentModelList = bookModel.getStudentModelList();
        if(!CollectionUtils.isEmpty(studentModelList)){

            studentModelList.forEach(s -> s.setBook_id(bookModel.getId()));
            studentMapper.addStudent(studentModelList);
        }

        }
    // 一对多的删除
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void deletes(List<Integer> ids) {
        studentMapper.deleteStudents(ids);
        studentMapper.deletes(ids);

    }
    // 一对多的回显
    @Override
    @LogOperation
    public BookModel getBookStudent(Integer id) {
        return studentMapper.getBookStudent(id);
        }

    // 一对多，修改
    @Override
    @LogOperation
    @Transactional(rollbackFor = {Exception.class})
    public void update(BookModel bookModel) {
        // 先跟新一
        bookModel.setAdd_time(LocalDate.now());
        studentMapper.update(bookModel);
        // 删除多
        studentMapper.deleteStudents(Arrays.asList(bookModel.getId()));
        List<StudentModel> studentModelList = bookModel.getStudentModelList();
        // 更新多
        if(!CollectionUtils.isEmpty(studentModelList)){
            studentModelList.forEach(s -> s.setBook_id(bookModel.getId()));
            studentMapper.addStudent(studentModelList);
            }
        }


}

